<?php


declare (strict_types=1);

namespace app\admin\controller;

use app\common\enum\file\FileType as FileTypeEnum;
use app\admin\service\Upload as UploadService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\response\Json;

/**
 * 文件库管理
 * Class Upload
 * @package app\store\controller
 */
class Upload extends Controller
{
    /**
     * 图片上传接口
     * @param int $groupId 文件库分组ID
     * @return Json
     * @throws Exception
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function image(int $groupId = 0): Json
    {
        // 执行文件上传
        $service = new UploadService();
        if (!$service->upload(FileTypeEnum::IMAGE, $groupId)) {
            return $this->renderError('文件上传失败：' . $service->getError());
        }
        // 图片上传成功
        return $this->renderSuccess(['fileInfo' => $service->getFileInfo()], '文件上传成功');
    }

    /**
     * 视频上传接口
     * @param int $groupId 文件库分组ID
     * @return Json
     * @throws Exception
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function video(int $groupId = 0): Json
    {
        // 执行文件上传
        $service = new UploadService();
        if (!$service->upload(FileTypeEnum::VIDEO, $groupId)) {
            return $this->renderError('文件上传失败：' . $service->getError());
        }
        // 图片上传成功
        return $this->renderSuccess(['fileInfo' => $service->getFileInfo()], '文件上传成功');
    }

    /**
     * Excel上传接口
     * @param int $groupId 文件库分组ID
     * @return Json
     * @throws Exception
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function excel(int $groupId = 0): Json
    {
        // 执行文件上传
        $service = new UploadService();
        if (!$service->upload(FileTypeEnum::EXCEL, $groupId)) {
            return $this->renderError('文件上传失败：' . $service->getError());
        }
        // 图片上传成功
        return $this->renderSuccess(['fileInfo' => $service->getFileInfo()], '文件上传成功');
    }

    /**
     * 附件上传接口
     * @param int $groupId 文件库分组ID
     * @return Json
     * @throws Exception
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function annex(int $groupId = 0): Json
    {
        // 执行文件上传
        $service = new UploadService();
        if (!$service->upload(FileTypeEnum::ANNEX, $groupId)) {
            return $this->renderError('文件上传失败：' . $service->getError());
        }
        // 图片上传成功
        return $this->renderSuccess(['fileInfo' => $service->getFileInfo()], '文件上传成功');
    }
}
